package com.nengjiang.wsplayer.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.nengjiang.wsplayer.Config;
import com.nengjiang.wsplayer.EventListener;
import com.nengjiang.wsplayer.R;
import com.nengjiang.wsplayer.utils.SimplePlayer;
import com.nengjiang.wsplayer.bean.LoginRequest;
import com.nengjiang.wsplayer.bean.LoginResponse;
import com.nengjiang.wsplayer.oksocket.OkManager;
import com.nengjiang.wsplayer.oksocket.Event;
import com.xuhao.didi.core.utils.SLog;

public class MainActivity extends AppCompatActivity {
    public static final String TAG = "MainActivity";

    private EditText mIPET;
    private EditText mPortET;

    private EditText mEtUserName;
    private EditText mEtPwd;

    private EventListener eventListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SLog.setIsDebug(true);
        initView();

        eventListener = new EventListener() {
            @Override
            public void onLoginRes(LoginResponse message) {
                showToast("登陆成");
            }

            @Override
            public void onConnectionSuccess() {
                showToast("链接服务器成功");
            }
        };


        OkManager.getInstance().addEventListener(eventListener);

    }

    private void initView() {
        mIPET = findViewById(R.id.ip);
        mPortET = findViewById(R.id.port);

        mEtUserName = findViewById(R.id.et_username);
        mEtPwd = findViewById(R.id.et_password);
    }


    public void connect(View view) {
        Config.SOCKET_URL = mIPET.getText().toString().trim();
        Config.SOCKET_PORT = Integer.valueOf(mPortET.getText().toString().trim());
        OkManager.getInstance().connect();

    }


    public void login(View view) {
        LoginRequest loginRequest = new LoginRequest(Event.EVENT_LOGIN_REQUEST);

        LoginRequest.LoginData loginData = new LoginRequest.LoginData();
        loginData.account = mEtUserName.getText().toString().trim();
        loginData.pwd = mEtPwd.getText().toString().trim();
        loginRequest.data = loginData;

        String message = new Gson().toJson(loginRequest);

        OkManager.getInstance().sendMessage(message);
    }

    public void goVideo(View view) {
        startActivity(new Intent(this, SimplePlayer.class));
    }

    private void showToast(String message) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkManager.getInstance().removeEventListener(eventListener);
    }
}


